import {Issue} from '@flow-step/step-toolkit/src/redline'
import {readHtmlFile} from '../src/utils'
import {count,parseAndUploadReport,modifyHtml} from '../src/parse-upload-report'
import {expect} from 'chai'
import {IParams} from '../src/params'
import sinon from 'sinon'
import fs from 'fs'
import * as step from '@flow-step/step-toolkit'
import path from 'path'

describe('count', () => {
    it('should count correctly', async () => {
        const data = await readHtmlFile('test/p3c-test.html')
        const result = count(data)
        const expectedResult:Issue = {
            total: 11,
            blocker: 0,
            critical: 0,
            major: 11,
        }
        expect(result).to.deep.equal(expectedResult)
    })
})

describe('modifyHtml', () => {
    it('should modify correctly', async () => {
        const data = await readHtmlFile('test/before_modification.html')
        const result = modifyHtml(data)
        const expectedResult = await readHtmlFile('test/expected_after_modification.html')
        expect(result).to.equal(expectedResult)
    })
})



describe('parseAndUploadReport', () => {
    let readHtmlFileStub: sinon.SinonStub;
    let existsSyncStub: sinon.SinonStub;
    let mkdirSyncStub: sinon.SinonStub;
    let writeFileSyncStub: sinon.SinonStub;
    let outputCodeScanResultStub: sinon.SinonStub;

    const mockParams: IParams = {
        projectDir: '/mock/project/dir',
        redline: "mock redline"
    }as unknown as IParams;

    beforeEach(() => {
        readHtmlFileStub = sinon.stub(require("../src/utils"),'readHtmlFile').resolves('<html><body><p>Mock HTML Content</p></body></html>');
        existsSyncStub = sinon.stub(fs, 'existsSync');
        mkdirSyncStub = sinon.stub(fs, 'mkdirSync');
        writeFileSyncStub = sinon.stub(fs, 'writeFileSync');
        outputCodeScanResultStub = sinon.stub(step.redline, 'outputCodeScanResult').resolves();
    });

    afterEach(() => {
        sinon.restore();
    });

    it('should parse and upload report correctly', async () => {
        const mockReportPath = '/mock/report/path';

        existsSyncStub.withArgs(path.join(mockParams.projectDir, 'tmp')).returns(false);
        existsSyncStub.withArgs(path.join(path.join(mockParams.projectDir, 'tmp'), path.basename(mockReportPath))).returns(false);

        await parseAndUploadReport(mockReportPath, mockParams);

        expect(readHtmlFileStub.calledOnceWithExactly(mockReportPath)).to.be.true;
        expect(mkdirSyncStub.calledOnceWithExactly(path.join(mockParams.projectDir, 'tmp'))).to.be.true;
        expect(writeFileSyncStub.calledOnceWithExactly(
            path.join(path.join(mockParams.projectDir, 'tmp'), path.basename(mockReportPath)),
            '<html><body><p>Mock HTML Content</p></body></html>'
        )).to.be.true;
        expect(outputCodeScanResultStub.calledOnce).to.be.true;
    });
});
